package 多线程;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * Created by Administrator on 2017/3/23.
 */
public class mycallable {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(10);
        List<Future<Long>> list = new ArrayList<Future<Long>>();
        for(long i=0; i < 10; i++){
            Callable<Long> worker = new testCallable(i*10+1, (i+1)*10);
            // 提交并执行任务，任务启动时返回了一个Future对象，
            Future<Long> submit = executor.submit(worker);
            list.add(submit);
        }
        long sum = 0;
        for(Future<Long> future : list){
            try{
                // 获得第任务的结果，如果调用get方法，当前线程会等待任务执行完毕后才往下执行
                sum += future.get();
            }catch (InterruptedException e1){
                e1.printStackTrace();
            }catch(ExecutionException e2){
                e2.printStackTrace();
            }
        }
        executor.shutdown();
    }
}
class testCallable implements Callable {
    private Long start;
    private Long end;
    public testCallable(Long start, long end){
        this.start = start;
        this.end = end;
    }
    public Long call()throws Exception{
        long sum = 0;
        for(long i = start; i <= end; i++){
            sum += i;
        }
        System.out.println(Thread.currentThread().getName() + " " +start + "-" + end + "=" + sum);
        return sum;
    }
}
